package com.education.platform.api.controller.course;

import com.education.platform.api.config.ThreadUser;
import com.education.platform.api.service.*;
import com.education.platform.api.service.common.CacheDataService;
import com.education.platform.api.vo.request.BuyCourseVO;
import com.education.platform.api.vo.request.CommitLearnTimeVO;
import com.education.platform.api.vo.request.CourseDetailQueryVO;
import com.education.platform.api.vo.request.CourseQueryVO;
import com.education.platform.api.vo.response.*;
import com.education.platform.common.enums.DicTypeEnum;
import com.education.platform.common.enums.OrderTypeEnum;
import com.education.platform.common.enums.PermissionTypeEnum;
import com.education.platform.common.enums.YesOrNoTypeEnum;
import com.education.platform.common.exception.BusinessException;
import com.education.platform.common.util.BeanUtil;
import com.education.platform.common.util.StringUtils;
import com.education.platform.dao.entity.*;
import com.education.platform.dao.model.CourseModel;
import com.education.platform.dao.model.CoursewareModel;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * describe: 课程
 *
 * @author : tomato
 * @date: 2020-06-17 12:13:04.723
 **/
@RestController
@Api("课程")
@RequestMapping("course")
@Validated
public class CourseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CourseController.class);

    @Autowired
    private CourseService courseService;

    @Autowired
    private CoursewareService coursewareService;
    @Autowired
    private CourseCommentService courseCommentService;
    @Autowired
    private CacheDataService cacheDataService;

    @Autowired
    private SysDictionaryService sysDictionaryService;


    @Autowired
    private ArticleService articleService;
    @Autowired
    private BuyService buyService;
    @Autowired
    private UserCountService userCountService;

    /**
     * 课程分页查询
     *
     * @param courseQueryVO 分页查询参数
     * @return 分页参数
     */
    @ApiOperation(value = "课程分页查询")
    @PostMapping("getPageList")
    public CoursePageInfoVO selectPageList(@RequestBody @Valid CourseQueryVO courseQueryVO) {
        CourseDO course = BeanUtil.convert(courseQueryVO, CourseDO.class);
        course.setDeleted(false);
        course.setPublish(true);
        //2021-5-5  将此接口分页条数改为50
        courseQueryVO.setPageSize(50);
        Page<CourseResponseVO> page = PageHelper.startPage(courseQueryVO.getPageNum(), courseQueryVO.getPageSize());
        CourseModel courseModel = BeanUtil.convert(course, CourseModel.class);
        if(ThreadUser.getUserTokenRedisKey()!=null){
            courseModel.setUserId(ThreadUser.getUserId());
        }
        List<CourseModel> courseList = courseService.getCourseList(courseModel);
        CoursePageInfoVO coursePageInfo = new CoursePageInfoVO();
        BeanUtils.copyProperties(page.toPageInfo(), coursePageInfo);
        List<CourseResponseVO> voList = BeanUtil.convert(courseList, CourseResponseVO.class);

        List<Integer> articleIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(voList)) {
            voList.parallelStream().forEach(vo ->
            {
                if (StringUtils.isNotEmpty(vo.getSubjectTypeName())) {
                    vo.setTags(Arrays.asList(vo.getSubjectTypeName().split(",")));
                }
                if(vo.getFileType()==2){
                    articleIds.add(vo.getDetailId());
                }

            });
        }
        //文章 需要从文章信息里 获取文章的浏览次数
        if(CollectionUtils.isNotEmpty(articleIds)){
          List<ArticleDO> articleDOS =  articleService.getListByIds(articleIds);
                articleDOS.parallelStream().forEach(article->{
                    voList.parallelStream().forEach(vo->{
                        if(article.getId().equals(vo.getDetailId())){
                            vo.setViewsNumber(article.getViewNumber());
                        }
                    });
                });
        }
        coursePageInfo.setList(voList);
        return coursePageInfo;
    }

    /**
     * 查询课程详情
     *
     * @param
     * @return
     */
    @ApiOperation(value = "查询课程详情")
    @PostMapping("getDetails")
    public CourseDetailsResponseVO getDetails(@RequestBody @Valid CourseDetailQueryVO detailQueryVO) {
        CourseDetailsResponseVO responseVO = new CourseDetailsResponseVO();

        CourseModel courseDTO = null;
        if (detailQueryVO.getCourseId() == null) {
            throw new BusinessException("课程id不能为空");
        }
        CourseModel query = new CourseModel();
        query.setId(detailQueryVO.getCourseId());
        query.setUserId(ThreadUser.getUserId());
        List<CourseModel> courseList = courseService.getCourseList(query);
        if(CollectionUtils.isEmpty(courseList)){
            throw new BusinessException("课程不存在");
        }
        courseDTO = courseList.get(0);
        //课程信息
        responseVO = BeanUtil.convert(courseDTO, CourseDetailsResponseVO.class);
        Integer courseId = courseDTO.getId();
        //课程选集集合
        CoursewareDO wareDTOquery = new CoursewareDO();
        wareDTOquery.setCourseId(courseId);
        List<CoursewareModel> details = coursewareService.getListByCourseIdAndUserId(courseId,
                StringUtils.isEmpty(ThreadUser.getUserTokenRedisKey()) ? null : ThreadUser.getUserId());

        //该课程 用户是否点赞，是否收藏。
        if (StringUtils.isEmpty(ThreadUser.getUserTokenRedisKey())) {
            //未登录
            responseVO.setCollectionStatus(YesOrNoTypeEnum.N.getValue());
            responseVO.setLikeStatus(YesOrNoTypeEnum.N.getValue());

        } else {
//            已登录
            responseVO.setCollectionStatus(cacheDataService.getCollectionStatus(courseId, 0));
            responseVO.setLikeStatus(cacheDataService.getLikeStatus(courseId, 0));

            //课程评论集合---自能看见自己的评论
            CourseCommentDO commentDTOquery = new CourseCommentDO();
            commentDTOquery.setCourseId(courseId);
            commentDTOquery.setUserId(ThreadUser.getUserId());
            List<CourseCommentDO> courseCommentDTOS = courseCommentService.getList(commentDTOquery);
            responseVO.setCommentResponseVOS(BeanUtil.convert(courseCommentDTOS, CourseCommentResponseVO.class));

        }
        //课程收藏数
        responseVO.setCollectionCount(cacheDataService.getCourseCollectCount(courseId));
        //课程点赞数
        responseVO.setLikeCount(cacheDataService.getCourseLikeCount(courseId));
        List<CoursewareResponseVO> coursewareResponseVOS = BeanUtil.convert(details, CoursewareResponseVO.class);
        if (CollectionUtils.isNotEmpty(coursewareResponseVOS)) {
            coursewareResponseVOS.parallelStream().forEach(m -> {
                //vip才能观看
                if (PermissionTypeEnum.VIP.getValue().equals(m.getPermissionType())) {
                    m.setUrl(null);
                }
            });
        }
        responseVO.setWareResponseVOS(coursewareResponseVOS);
        //课程标签
        responseVO.setTags(Collections.emptyList());
        if (StringUtils.isNotEmpty(courseDTO.getSubjectTypeName())) {
            responseVO.setTags(Arrays.asList(courseDTO.getSubjectTypeName().split(",")));
        }
        if (detailQueryVO.getType() == 1) {
            responseVO.setCreateTime(null);
            responseVO.setViewsNumber(null);
        }
        //浏览次数
        CourseDO updateCourse = new CourseDO();
        updateCourse.setId(courseId);
        updateCourse.setViewsNumber(courseDTO.getViewsNumber() == null ? 0 : courseDTO.getViewsNumber() + 1);
        courseService.updateById(updateCourse);
        return responseVO;
    }



    /**
     * 提交记录学习时长
     *
     * @param
     * @return 分页参数
     */
    @ApiOperation(value = "提交记录学习时长")
    @PostMapping("commitLearnTime")
    public boolean commitLearnTime(@RequestBody @Valid CommitLearnTimeVO timeVO) {
        //保存到数据库
        UserCountDO count = new UserCountDO();
        count.setUserId(ThreadUser.getUserId());
        count.setTodayLearnTime((float)timeVO.getTime());
        count.setTotalLearnTime((float)timeVO.getTime());
        return userCountService.updateLearnTime(count);
    }


    /**
     * 获取观看链接
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取vip视频播放链接")
    @GetMapping("getViewUrl")
    public QiNiuResponseVO getViewUrl(@RequestParam @NotNull(message = "文件id不能为null") @ApiParam("文件id") Integer corsewareId) {
        String url = coursewareService.getQiNiuUrl(corsewareId);
        QiNiuResponseVO responseVO = new QiNiuResponseVO();
        responseVO.setLink(url);
        return responseVO;
    }




    @ApiOperation(value = "获取年级")
    @PostMapping("selectGrade")
    public List<SysDictionaryResponseVO> selectGrade() {
        Map<String, List<SysDictionaryResponseVO>> map = new HashMap<>(2);
        List<String> typeCodes = Arrays.asList(DicTypeEnum.MIDDLE_GRADE.getValue(), DicTypeEnum.HIGH_GRADE.getValue());
        List<SysDictionaryDO> dictionaryDTOS = sysDictionaryService.getListByDicTypeCodeList(typeCodes);
        List middles = dictionaryDTOS.parallelStream().filter(m -> DicTypeEnum.MIDDLE_GRADE.getValue().equals(m.getTypeCode())).collect(Collectors.toList());
        List highs = dictionaryDTOS.parallelStream().filter(m -> DicTypeEnum.HIGH_GRADE.getValue().equals(m.getTypeCode())).collect(Collectors.toList());

        middles = BeanUtil.convert(middles, SysDictionaryResponseVO.class);
        highs = BeanUtil.convert(highs, SysDictionaryResponseVO.class);
        List<SysDictionaryResponseVO> result = new ArrayList<>();
        result.addAll(middles);
        result.addAll(highs);
        return result;
    }


    @ApiOperation(value = "获取中考分类")
    @GetMapping("selectMiddleExamType")
    public List<SysDictionaryResponseVO> selectMiddleExamType() {
        List<String> typeCodes = Arrays.asList( DicTypeEnum.MIDDLE_EXAM.getValue());
        List<SysDictionaryDO> dictionaryDTOS = sysDictionaryService.getListByDicTypeCodeList(typeCodes);
        List<SysDictionaryResponseVO>  middles = BeanUtil.convert(dictionaryDTOS, SysDictionaryResponseVO.class);
        return middles;
    }
    @ApiOperation(value = "获取高考分类")
    @GetMapping("selectHighExamType")
    public List<SysDictionaryResponseVO> selectHighExamType() {
        List<String> typeCodes = Arrays.asList( DicTypeEnum.HIGH_EXAM.getValue());
        List<SysDictionaryDO> dictionaryDTOS = sysDictionaryService.getListByDicTypeCodeList(typeCodes);
        List<SysDictionaryResponseVO>  middles = BeanUtil.convert(dictionaryDTOS, SysDictionaryResponseVO.class);
        return middles;
    }



    /**
     * 购买课程
     * @param
     * @return 分页参数
     */
    @ApiOperation(value = "购买课程")
    @PostMapping("buyCourse")
    public Boolean buyExamPaper(@RequestBody @Valid BuyCourseVO buyCourseVO) {
       return buyService.buyProduct(OrderTypeEnum.COURSE_ORDER.getValue(),buyCourseVO.getId(),buyCourseVO.getTotalPrice());
    }

}
